//
//  HCHomeViewController.m
//  HappyChildren
//
//  Created by WillyZhao on 2016/12/16.
//  Copyright © 2016年 WillyZhao. All rights reserved.
//

#import "HCHomeViewController.h"

#import "YBKPPTVC.h"
#import "HCHomeMiddleView.h"
#import "HCSanimationView.h"
#import "HCContentButton.h"
#import "HCHomeBottomView.h"
#import "AppDelegate.h"

#import "HCHomeNewsModel.h"

#import "HCGoodsListModel.h"
#import "XFWkwebView.h"
#import <AFNetworking.h>
#import "HCHomeWkWebView.h"
#import "HCPopLoadingView.h"

#import "HCHomeAlGrowModel.h"
#import "HCAlGrowCollectionViewCell.h"

@interface HCHomeViewController () <HCHomeBottomViewSizeDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HCHomeWkWebViewHeight,HCSanimationViewClicked,HCHomeMiddleViewDelegate> {
    __weak  UIView *pptView;
    HCHomeAlGrowModel *alGrowModel;             //首页推荐成长相册model
    YBKPPTVC *pptvc;//banner图
    UIScrollView *contentScrollView;
    HCHomeBottomView *bottomView;
    NSMutableArray *images;
    
    HCHomeNewsModel *newsModel;
    HCSanimationView *an;
    UIView *vc;
    
    HCGoodsListModel *goodsModel;
    
    HCHomeWkWebView *web;
    MBProgressHUD *homeHud;
    UICollectionView *alGrowCollection_;
    UICollectionView *homeVrCollection_;
    
    UIImageView *advertiseImageView1;
    UIImageView *advertiseImageView2;
    UIImageView *advertiseImageView3;
    
    NSArray *advertiseArray;
}

@end

@implementation HCHomeViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.dataRequest.delegate = self;
    [self.dataRequest postHC_Vipcheck:[NSString stringWithFormat:@"%@",HCGETUSER(@"hcphone")]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    
    self.textTitle = @"首页";
    //页面加载
    CGRect frame =  [self initBannerPic]; //banner
    frame = [self initCollectionView:frame]; //中间工具栏
    frame = [self initAdvertiseImageView:frame]; //广告图1
    frame = [self alGrothRepain:frame]; //成长相册
    frame = [self initAdvertise2:frame]; //广告图2
    frame = [self initVRaBOUT:frame]; //VR展示
    frame = [self initAdvertise3:frame]; //广告图3
    [self initWkWebView:frame];
}

#pragma mark 网络请求返回
-(void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    
    if (aType == HC_HOMEADVERTISE_TYPE) {
        
        if (dictionary) {
            
            NSArray *arr = [dictionary objectForKey:@"pic"];
            [self setHomeAdvertiseImagesWithArray:arr];
            advertiseArray = [NSArray arrayWithArray:arr];
        }
        
        [self.dataRequest postHC_BannerGet];
        
    }else if(aType == HC_HOMEVIPCHECK_TYPE){

        if ([dictionary[@"vip"] integerValue] == 200) {
            HCUSERDEFUALTS(@"yes", @"hcvip");
        }else{
            HCUSERDEFUALTS(@"no", @"hcvip");
        }
        
        [self.dataRequest post_HCHomeGetAdvertiseImages];
        
    }else if (aType == HC_GETBANNERSS_TYPE) {
        NSLog(@"banner获取成功:%@",dictionary);
        NSArray *ar = [NSArray arrayWithArray:dictionary[@"pic"]];
        
        pptvc.showModelArray = ar;
        [self.dataRequest postHC_AlGrowAbout];
        
    }else if(aType == HC_HOMEALGROW_TYPE){
        
        NSLog(@"首页成长相册获取:%@",dictionary);
        alGrowModel = [[HCHomeAlGrowModel alloc] initWithDictionary:dictionary error:nil];
        if (alGrowCollection_) {
            [alGrowCollection_ reloadData];
            
            // 获取商品详情
            [self.dataRequest postHC_Goods];
        }
    }else{
        
        goodsModel = [[HCGoodsListModel alloc] initWithDictionary:dictionary error:nil];
        bottomView.model_goods = goodsModel;
    }
}

-(void)dataRequesterFail:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveErrorDictionary:(NSDictionary *)dictionary {
    
    if (aType == HC_HOMEADVERTISE_TYPE) {
        
        [self.dataRequest postHC_BannerGet];
    }
    else if(aType == HC_HOMEVIPCHECK_TYPE){
        
        [self.dataRequest post_HCHomeGetAdvertiseImages];
    }
    else if (aType == HC_GETBANNERSS_TYPE) {

        [self.dataRequest postHC_AlGrowAbout];
        
    }
    else if(aType == HC_HOMEALGROW_TYPE){
        
        alGrowModel = [[HCHomeAlGrowModel alloc] initWithDictionary:dictionary error:nil];
        if (alGrowCollection_) {
            [alGrowCollection_ reloadData];
            
            // 获取商品详情
            [self.dataRequest postHC_Goods];
        }
    }
}

- (void)setHomeAdvertiseImagesWithArray:(NSArray *)imageData {

    for (int i = 0; i < imageData.count; i++) {
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[imageData[i] objectForKey:@"path"]]];
        if (i == 0) {
            
            [advertiseImageView1 sd_setImageWithURL:url placeholderImage:nil];
        }
        if (i == 1) {
            
            [advertiseImageView2 sd_setImageWithURL:url placeholderImage:nil];
        }
        if (i == 2) {
            
            [advertiseImageView3 sd_setImageWithURL:url placeholderImage:nil];
        }
        NSLog(@"urls:%@",url);
    }
}

#pragma mark 初始化banner图片
-(CGRect)initBannerPic {
    
    contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.centerView.frame.size.width, self.centerView.frame.size.height)];
//    contentScrollView.scrollEnabled = NO;
    contentScrollView.showsVerticalScrollIndicator = NO;
    [self.centerView addSubview:contentScrollView];
    
    pptvc = [[YBKPPTVC alloc] init];
    __weak YBKPPTVC *p= pptvc;
//    __weak HCHomeViewController *ss = self;

    pptvc.clickBlock = ^(HCHomeBannerModel *model) {
        NSLog(@"点击了");
//        p.pptPageControl.currentPage = 
    };
    
    pptvc.scrollBlock = ^(NSInteger m) {
//        NSLog(@"滑动");
        p.pptPageControl.currentPage = m;
    };
    
    //这里-20是一个bug
    pptvc.view.frame=CGRectMake(0, 0,self.centerView.bounds.size.width, YBKAdaptiveH(160));
    pptView=pptvc.view;
    pptvc.view.backgroundColor = [UIColor lightGrayColor];
    [self addChildViewController:pptvc];
    [pptvc didMoveToParentViewController:self];
    [contentScrollView addSubview:pptvc.view];
    return pptvc.view.frame;
}

//重置页面高度
-(void)hc_homeWkHeight:(CGFloat)height {
    
    web.frame = CGRectMake(web.frame.origin.x, web.frame.origin.y, web.frame.size.width, height);
    web.wkWebView.frame = CGRectMake(0, 0, web.frame.size.width, height);
    contentScrollView.contentSize = CGSizeMake(self.centerView.frame.size.width, web.frame.origin.y+web.frame.size.height+10);
    [homeHud hide:YES];
}

#pragma mark 成长相册推荐
//初始化成长相册推荐
-(CGRect)alGrothRepain:(CGRect)frame {
    
    vc = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, self.centerView.frame.size.width, YBKAdaptiveH(180))];
    vc.backgroundColor = [UIColor whiteColor];
    [contentScrollView addSubview:vc];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.minimumLineSpacing = 10;
    flow.minimumInteritemSpacing = 10;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    alGrowCollection_ = [[UICollectionView alloc] initWithFrame:CGRectMake(0, YBKAdaptiveH(30), self.centerView.frame.size.width, YBKAdaptiveH(150)) collectionViewLayout:flow];
    alGrowCollection_.delegate = self;
    alGrowCollection_.dataSource = self;
    alGrowCollection_.tag = 1;
    alGrowCollection_.showsHorizontalScrollIndicator = NO;
    alGrowCollection_.backgroundColor = [UIColor whiteColor];
    [vc addSubview:alGrowCollection_];
    [alGrowCollection_ registerNib:[UINib nibWithNibName:@"HCAlGrowCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cellalg"];
    
    UIImage *image = [UIImage imageNamed:@"成长相册推荐"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, (YBKAdaptiveH(30) - image.size.height)/2.0+YBKAdaptiveH(2), image.size.width, image.size.height);
    [vc addSubview:imageView];
    return vc.frame;
}

- (CGRect)initAdvertise2:(CGRect)frame {

    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, Screen_width, YBKAdaptiveH(92))];
    backView.backgroundColor = [UIColor whiteColor];
    [contentScrollView addSubview:backView];
    
    advertiseImageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(5, YBKAdaptiveH(9)/2.0, Screen_width-10, YBKAdaptiveH(83))];
    advertiseImageView2.backgroundColor = YBKRGBCOLOR(240, 240, 240, 1);
    advertiseImageView2.contentMode = UIViewContentModeScaleAspectFill;
    advertiseImageView2.layer.masksToBounds = YES;
    [backView addSubview:advertiseImageView2];
    
    advertiseImageView2.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick2)];
    [advertiseImageView2 addGestureRecognizer:tap];
    
    return backView.frame;
}

#pragma mark VR按钮
-(CGRect)initVRaBOUT:(CGRect)frame {
    
    UIView *vgf = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, self.centerView.frame.size.width, YBKAdaptiveH(180))];
    vgf.backgroundColor = [UIColor whiteColor];
    [contentScrollView addSubview:vgf];
    
    UIImage *image = [UIImage imageNamed:@"VR展示"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, (YBKAdaptiveH(30) - image.size.height)/2.0+YBKAdaptiveH(2), image.size.width, image.size.height);
    [vgf addSubview:imageView];
    
    images = [NSMutableArray array];
    
    for (int i = 0; i<4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"VR%d",i]];
        [images addObject:image];
    }
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.minimumLineSpacing = 10;
    flow.minimumInteritemSpacing = 10;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    homeVrCollection_ = [[UICollectionView alloc] initWithFrame:CGRectMake(0, YBKAdaptiveH(30), self.centerView.frame.size.width, YBKAdaptiveH(150)) collectionViewLayout:flow];
    homeVrCollection_.delegate = self;
    homeVrCollection_.dataSource = self;
    homeVrCollection_.tag = 2;
    homeVrCollection_.showsHorizontalScrollIndicator = NO;
    homeVrCollection_.backgroundColor = [UIColor whiteColor];
    [vgf addSubview:homeVrCollection_];
    
    [homeVrCollection_ registerNib:[UINib nibWithNibName:@"HCAlGrowCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cellalg"];
    return vgf.frame;
}

- (CGRect)initAdvertise3:(CGRect)frame {
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, Screen_width, YBKAdaptiveH(92))];
    backView.backgroundColor = [UIColor whiteColor];
    [contentScrollView addSubview:backView];
    
    advertiseImageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(5, YBKAdaptiveH(9)/2.0, Screen_width-10, YBKAdaptiveH(83))];
    advertiseImageView3.backgroundColor = YBKRGBCOLOR(240, 240, 240, 1);
    advertiseImageView3.contentMode = UIViewContentModeScaleAspectFill;
    advertiseImageView3.layer.masksToBounds = YES;
    [backView addSubview:advertiseImageView3];
    
    advertiseImageView3.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick3)];
    [advertiseImageView3 addGestureRecognizer:tap];
    
    return backView.frame;
}

#pragma mark -- 点击VR
-(void)VRButtonAction:(UIButton *)btn {
    NSLog(@"VR");
    [self pushChildrenViewController:@"HCVRViewController" parameterObject:nil dataObject:nil];
}

#pragma mark --点击广告图片
- (void)imageClick1 {

    if (advertiseArray.count >= 1) {
        
        NSString *url = [[advertiseArray objectAtIndex:0] objectForKey:@"url"];
        [self pushChildrenViewController:@"HCHomeAdvertiseController" parameterObject:url dataObject:nil];
    }
}

- (void)imageClick2 {

    if (advertiseArray.count >= 2) {
        
        NSString *url = [[advertiseArray objectAtIndex:1] objectForKey:@"url"];
        [self pushChildrenViewController:@"HCHomeAdvertiseController" parameterObject:url dataObject:nil];
    }
}

- (void)imageClick3 {
    
    if (advertiseArray.count >= 3) {
        
        NSString *url = [[advertiseArray objectAtIndex:2] objectForKey:@"url"];
        [self pushChildrenViewController:@"HCHomeAdvertiseController" parameterObject:url dataObject:nil];
    }
}

#pragma mark UICollectionDelegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView.tag == 1) {
        if (alGrowModel) {
            return alGrowModel.grow_show.count;
        }else{
            return 0;
        }
    }else{
        return images.count;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 1) {
        return CGSizeMake(YBKAdaptiveH(220), YBKAdaptiveH(140));
    }else{
        if (indexPath.row == 0) {
            return CGSizeMake(YBKAdaptiveH(140), YBKAdaptiveH(140));
        }else{
            return CGSizeMake(YBKAdaptiveH(220), YBKAdaptiveH(140));
        }
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 10, 0, 10);
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 1) {
        HCAlGrowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellalg" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        if (alGrowModel) {
            HCHomeAlGrowData *data = alGrowModel.grow_show[indexPath.row];
            cell.model = data;
        }
        
        return cell;
    }else{
        HCAlGrowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellalg" forIndexPath:indexPath];
        cell.alName.hidden = YES;
        cell.alHeadIMG.hidden = YES;
        cell.contentImageViewSS.image = images[indexPath.row];
        cell.backgroundColor = [UIColor blackColor];
        return cell;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (collectionView.tag == 1) {
        HCHomeAlGrowData *data = alGrowModel.grow_show[indexPath.row];
        [self pushChildrenViewController:@"HCALDetailViewController" parameterObject:data.url dataObject:nil];
    }else{
        [self pushChildrenViewController:@"HCVRViewController" parameterObject:nil dataObject:nil];
    }
}

//传值跳转
-(void)hc_homeWKClicked:(NSString *)url {
    XFWkwebView *wkWeb = [[XFWkwebView alloc] init];
    [wkWeb loadWebURLSring:url];
    [self.navigationController pushViewController:wkWeb animated:YES];
//    [web wkWebViewLoadString:@"http://www.chaojimatou.com/mobile/goods_cat.php?c_id=1731&nohead=1"];
}

-(void)initWkWebView:(CGRect)frame {
    
#warning 商城
    bottomView = [[HCHomeBottomView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, self.self.centerView.frame.size.width, self.centerView.frame.size.height)];
    bottomView.dataSource = self;
    [contentScrollView addSubview:bottomView];
}

#pragma mark 商品列表点击
-(void)goodsViewClicked:(NSIndexPath *)indexPath {
    NSLog(@"商品点击了");
    
   HCGoodsListData *data = goodsModel.goods[indexPath.row];
    NSString *qid = [NSString stringWithFormat:@"%@",data.hc_id];
    [self pushChildrenViewController:@"HCGGoodsDetailViewController" parameterObject:qid dataObject:data.url];
}

-(CGRect)initCollectionView:(CGRect)frame {
    
    HCHomeMiddleView *collectionView = [[HCHomeMiddleView alloc] initWithFrame:CGRectMake(0, frame.origin.y+frame.size.height, frame.size.width, YBKAdaptiveH(78))];
    collectionView.delegate = self;
    [contentScrollView addSubview:collectionView];
    return collectionView.frame;
    
}

//广告图片
- (CGRect)initAdvertiseImageView:(CGRect)frame {

    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(frame)+4, Screen_width, YBKAdaptiveH(92))];
    backView.backgroundColor = [UIColor whiteColor];
    [contentScrollView addSubview:backView];
    
    advertiseImageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(5, YBKAdaptiveH(9)/2.0, Screen_width-10, YBKAdaptiveH(83))];
    advertiseImageView1.backgroundColor = YBKRGBCOLOR(240, 240, 240, 1);
    advertiseImageView1.contentMode = UIViewContentModeScaleAspectFill;
    advertiseImageView1.layer.masksToBounds = YES;
    [backView addSubview:advertiseImageView1];
    
    advertiseImageView1.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClick1)];
    [advertiseImageView1 addGestureRecognizer:tap];
    
    return backView.frame;
}
//新闻中心
-(CGRect)initializeScrollAnimationView:(CGRect)frame {
    
    an = [[HCSanimationView alloc] initWithFrame:CGRectMake(0, frame.origin.y+frame.size.height+3, YBKWinFrame.size.width, YBKAdaptiveH(60))];
    an.delegate = self;
    
    __weak typeof (self)weakSelf = self;
    an.block = ^(){
        
        [weakSelf pushChildrenViewController:@"HCNewsListViewController" parameterObject:nil dataObject:nil];
    };
    [contentScrollView addSubview:an];
    return an.frame;
}

#pragma mark HCHomeBottomViewSizeDataSource
-(void)homeBottomViewSize:(CGFloat)height bottomView:(HCHomeBottomView *)homeBottomView {
    bottomView.frame = CGRectMake(0, bottomView.frame.origin.y, bottomView.frame.size.width, height);
    contentScrollView.contentSize = CGSizeMake(bottomView.frame.size.width, height+bottomView.frame.origin.y);
}

#pragma mark HCHomeMiddleViewDelegate
-(void)middleViewButtonsClicked:(HCHomeMiddleViewClickType)clickStyle {
    
    switch (clickStyle) {
        
            //育儿宝箱
        case HCHomeMiddleViewKnowledge:
        {
//            if (![ PublicFunction isNull:HCGETUSER(@"userid")]) {
//                [self pushChildrenViewController:@"HCStarViewController" parameterObject:nil dataObject:nil];
//                
//            }else{
                [XHToast showBottomWithText:@"敬请期待"];
//            }
        }
            break;
        case HCHomeMiddleViewImages:
            //成长相册
        {
            if (![PublicFunction isNull:HCGETUSER(@"userid")]) {
                [self pushChildrenViewController:@"HCGrowthAlbumViewController" parameterObject:nil dataObject:nil];
            }else{
                [XHToast showBottomWithText:@"请先登录"];
            }
        }
            break;
        case HCHomeMiddleViewOnline:
            //在线预约
        {
            AppDelegate *app = (AppDelegate *)[[UIApplication  sharedApplication] delegate];
            [app.rootVC selectedIndexPath:102];
        }
            break;
        case HCHomeMiddleViewMessages:
            //消息中心
        {
            [self pushChildrenViewController:@"HCMessageCenterViewController" parameterObject:nil dataObject:nil];
        }
            break;
        default:
            break;
    }
}

-(void)animationViewClicked:(NSInteger)index {
    HCHomeNewsData *data = newsModel.index[index];
    [self pushChildrenViewController:@"HCNeswDetailViewController" parameterObject:data.url dataObject:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
